package utils;

import android.os.AsyncTask;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.ygk.bluepath.core.BPresenter;
import com.ygk.bluepath.core.BPresenterFragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import utils.ui.view.ProDialog_logo;

public class PostFormForPresenterFragmentUtil extends AsyncTask<Void, Integer, JSONObject> {
    JSONObject js=new JSONObject();
    String oid = "";
    String url = "";
    Object extraStr;
    BPresenterFragment mPresenter;
    boolean canCancel = true;
    boolean showLoading = false;

    private HashMap<String, Object> picsMaps;
    private HashMap<String, Object> map;

    private MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    private final OkHttpClient client = new OkHttpClient();

    private String CHARSET = "utf-8"; // 设置编码

    @SuppressWarnings("unchecked")
    public PostFormForPresenterFragmentUtil(BPresenterFragment mPresenter, String url, HashMap<String, Object> map,
                                            boolean canCancel, boolean showLoading, String oid, Object extraStr) {
        super();
        this.url = url.contains("http:")?url:Inf.URLHEAD + url;
        this.map = map;
        this.picsMaps = (HashMap<String, Object>) map.get("picsMaps");
        this.mPresenter = mPresenter;
        this.canCancel = canCancel;
        this.showLoading = showLoading;
        this.oid = oid;
        this.extraStr = extraStr;

    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        if (!PhoneInformationUtil.isNetworkAvailable()) {
            if (mPresenter != null) {
                mPresenter.tt("网络未连接,请检查网络!");
                mPresenter.dealJsonObject(null, oid, extraStr);
            }
            return;
        }
        if (showLoading) {
            if (canCancel) {
                ProDialog_logo.show(mPresenter.getActivity(),
                        true);
            } else {
                ProDialog_logo.show(mPresenter.getActivity(), false);
            }
        }
    }

    @Override
    protected void onCancelled() {
        // TODO Auto-generated method stub
        super.onCancelled();
        if (showLoading) {
            ProDialog_logo.close();
        }
        if (mPresenter != null) {
            mPresenter.dealJsonObject(null, oid, extraStr);
        }
    }

    protected void onPostExecute(JSONObject result) {
        ProDialog_logo.close();
        if (mPresenter != null) {
            mPresenter.dealJsonObject(result, oid, extraStr);
        }

    }

    @SuppressWarnings("unchecked")
    @Override
    protected JSONObject doInBackground(Void... params) {
        // TODO Auto-generated method stub

        JSONObject jsonObject = null;
        // instantiate HttpPost object from the url address
        MultipartBuilder mpb = new MultipartBuilder().type(MultipartBuilder.FORM);
        /*
		 * .addFormDataPart("imei",Tools.base64Encode(IdouApp.getInstance().
		 * getSharedPre().getimei()))
		 * .addFormDataPart("key",Tools.base64Encode(Tools
		 * .EnAndDe(IdouApp.getInstance().getSharedPre().getToken())))
		 * .addFormDataPart(
		 * "avatar","avatar.jpg",RequestBody.create(MEDIA_TYPE_PNG, new
		 * File(val))) ;
		 */
        LogUtils.i("url::" + url);
        // 解析map中的数据
        if (map != null) {


            Set<String> key_set = map.keySet();

            for (Iterator<String> it = key_set.iterator(); it.hasNext(); ) {

                String key = it.next();

                if (key == null || key.equals("")) {
                    LogUtils.i(key + "key+++null");
                    return jsonObject;
                } else {
                    if (map.get(key) == null) {
                        LogUtils.i(map.get(key) + "++map.get(key)");
                        return jsonObject;
                    } else {
                        LogUtils.i(key + "::" + map.get(key));
                        try {
                            if (key.equals("picsMaps")){
                                continue;
                            }
                            js.put(key, map.get(key).toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                       // mpb.addFormDataPart(key, map.get(key).toString());
                    }
                }
            }
            LogUtils.i("Json::" + js.toString());
           // mpb.addFormDataPart("sign", js.toString());
        }

        // 图片集合
        if (picsMaps != null) {
            Set<String> key_setPics = picsMaps.keySet();
            for (Iterator<String> it = key_setPics.iterator(); it.hasNext(); ) {

                String key = it.next();

                if (key == null || key.equals("")) {
                    LogUtils.i(key + "key+++null");
                    return jsonObject;
                } else {
                    if (picsMaps.get(key) == null) {
                        LogUtils.i(picsMaps.get(key) + "++map.get(key)");
                        return jsonObject;
                    } else {

                        Object object = picsMaps.get(key);
                        if (object instanceof String) {
                            LogUtils.i("SinglePic-" + key + "::" + object.toString());
                            mpb.addFormDataPart(key, "main.jpg",
                                    RequestBody.create(MEDIA_TYPE_PNG, new File(object.toString())));
                        } else if (object instanceof List) {
                            List<String> mPicList = (List<String>) object;
                            LogUtils.i("Pic-" + key + "::" + mPicList.size());
                            if (mPicList.size() == 0) {
                                LogUtils.i("addNone");
                                mpb.addFormDataPart(key, "", new MultipartBuilder().type(MultipartBuilder.FORM)
                                        .addFormDataPart(key, "").build());

                            } else

                                for (String filePath : mPicList) {
                                    LogUtils.i(key + "::" + filePath);
                                    mpb.addFormDataPart(key,
                                            "ach_" + filePath.substring(filePath.lastIndexOf("/")) + ".jpg",
                                            RequestBody.create(MEDIA_TYPE_PNG, new File(filePath)));
                                }
                        }

                    }
                }
            }
        }


        try {
            url=url+"?sign="+URLEncoder.encode(js.toString(),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = mpb.build();
        Request request = new Request.Builder()
                // .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
                .url(url).post(requestBody).build();
        try {
            client.setConnectTimeout(5, TimeUnit.SECONDS);
            client.setReadTimeout(5, TimeUnit.SECONDS);
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String strResult = response.body().string();
                LogUtils.i(url + "-ResultString::" + strResult);
                jsonObject = new JSONObject(strResult);
            } else {
                LogUtils.i("Error Response:" + response.body().string());
            }
        } catch (SocketTimeoutException e) {
            // TODO: handle exception
            mPresenter.tt("网络连接超时");
        } catch (IOException | JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonObject;

    }

}
